/** @jsxImportSource @emotion/react */
//入口的起始主页面；

import {  Global } from "@emotion/react";
import * as React from "react";
//import { Link as RouterLink } from "@reach/router";
//使用RouterLink不会强制刷新页面的。
import { Link as RouterLink } from "wouter";
import food from "./images/food.svg";
import {
    Navbar,
    Toolbar,
    Text, Button,
    useTheme,
    useResponsiveBodyPadding,
    Container,
    Link,   　　　//这里sancho的Link等同于基础的<a><a/>，会跳转重新刷新页面；
    IconArrowRight, IconGift, IconTruck, IconPrinter, IconKey, InputGroup, Input, Alert
} from "customize-easy-ui-component";
import { 首页末尾链接 } from "../comp/rootRarelyVary";


import useLoginMutation from "./useLoginMutation";
import {useContext, useState} from "react";
import {UserContext} from "../context/UserContext";
//密码hash 防止在服务后台泄密
var sha256 = require('hash.js/lib/hash/sha/256');


interface BrandingProps {
}
export const Branding: React.FunctionComponent<BrandingProps> = (props) => {
    const {user, setUser} =useContext(UserContext);
    //我的身份合法吗
    const [isMeUser, setIsMeUser] =React.useState(user!==null);
    const theme = useTheme();
    const [isRegistering, setIsRegistering] = React.useState(
        false
    );
    const [form, setForm] = React.useState({ username: "", password: "",
        mobile:'', external:'旧平台'} as any);
    const [redirectToReferrer, setRedirectToReferrer] = React.useState(false);

    const {call:submitfunc, isInFlight}= useLoginMutation();
    //用<form> 来提交，这样required属性就能生效了，能够验证表单的内容。
    //登录要对userContext/useSession 切换；
    async function doLogin(e: React.FormEvent  | Event)
    {
        e.preventDefault();
        setIsMeUser(false);
        let encodePass=sha256().update(form.password).digest('hex');
        try {

            await  submitfunc(form.username, encodePass);
            //运行到这还未必真的有应答的, 很特别！！
            //这里捕捉到的 isInFlight还是在本函数进入之前的那个瞬态=false; 可函数外面实际还在isInFlight=true??
            console.log("submitfunc 登录 下一步= isInFlight函数内=",isInFlight);
            setRedirectToReferrer(true);
          //  setRedirectToReferrer(true);
        } catch (err) {

        }
    }
  console.log("路由进入 登录伪2页面= isInFlight外部=",isInFlight,"user=",user);
    //都可能无法刷新？ <Redirect  to={from.pathname} />;  setLocation (to: Path, replace?: boolean)
    React.useEffect(() => {
        if(user && !isMeUser)
            window.location.href = "/";       //强制刷新页面。
        //登录失败的？
    }, [user,isMeUser]);

  return (
      <main>
        <Global
            styles={{
              html: {
                backgroundColor: theme.colors.background.tint1
              }
            }}
        />

          <form  method="post"
                 onSubmit={e =>{ doLogin(e) } }>
              <div   css={{  marginTop: theme.spaces.md   }}>
                   <InputGroup  label={isRegistering ?'申请本平台账户名字':"账户"}>
                      <Input  required
                              onChange={e => {
                                  setForm({ ...form, username: e.currentTarget.value });
                              }}
                              value={form.username}
                              inputSize="md"
                              type="text"
                          //浏览器HTML5验证格式是否正确input type="email" required multiple/>
                              placeholder="账户"
                      />
                  </InputGroup>
                  <InputGroup hideLabel={!isRegistering} label={isRegistering ?'设置登录密码(强度不合格会报错)':"密sdfsd码"}>
                      <Input  required
                              onChange={e => {
                                  setForm({ ...form, password: e.currentTarget.value });
                              }}
                              value={ form.password }
                              inputSize="md"
                              type="password"
                          //type={ form.password? "password":"text"}强制要求输入密码，不采用浏览器填充记住的密码。
                              placeholder="密码最少6位的复杂的 asdasdasda"
                              autoComplete="off"
                      />
                  </InputGroup>

                  <div css={{ display: "flex", justifyContent: "flex-end" }}>
                      <Button
                          disabled={!form.username || !form.password}
                          block
                          component="button"
                          css={{
                              textAlign: "center",
                              width: "100%",
                              marginTop: theme.spaces.md
                          }}
                          type="submit"
                          size="md"
                          intent="primary"
                          //onPress={e =>{isRegistering ? doRegister(e) : doLogin(e) } }
                      >
                          {isRegistering ? "注册申请" : "登录"}
                      </Button>
                  </div>
              </div>
          </form>
        {首页末尾链接()}
      </main>
  );
};

//用于动态加载，缺省的
export default Branding;



//<Link  from "customize-easy-ui-component UI"是<a>跳转刷新=级别高的。而{Link as RouterLink }from "wouter @reach/router"是APP内部转移，节省资源=能保持context。
//css修饰体内部的 "& > div": { },  表示 当前元素的子代元素div，对它附加样式{ };
/*上面responsiveBodyPadding（内定好的空挡留白）带入的添加： 　{ padding-top:56px;} 　以及
  <style data-emotion="css">@media (min-width:768px){.css-adq7pz-Branding{padding-top:64px;}}</style>　顶部留出64px；分成两个尺寸。
*/
//模拟A4打印机窗口大小。A4，边距=无，缩放=默认。exact-width:595px; A4，边距=无，缩放=70%。exact-width:850px;不算大哦，差不多就是810px宽度。看着像1142px*1590px。
//打印机的所用代码宽度px实际很小的，没有缩放可能才600px的。["@media print and (min-width:551px)and (max-width:849px)"]: {display: "none",}
//<RouterLink   to="/device/">    <Button />  />   这里： 实际向Button会注入{ onClick=navigate(href) }； 估计useTouchable的bind导致异常。


